using System;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;

/* class to check at page if a user is logged in */
public static class IsLoggedIn {

	/// <summary>
	/// Check if a user supplied cookie is valid
	/// </summary>
	/// <param name="cookie">login cookie</param>
	/// <returns>if user is logged in or not</returns>
	public static bool Check(HttpCookie cookie)
	{
		if (cookie == null) return false; // no cookie, new user

		String md5hashHex;

		// Get cookie
		String[] tokens = cookie.Value.Split(new char[] { ':' });

		// Get MD5 provider
		MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider();
		md5hashHex = RC4.bin2hex(Encoding.GetEncoding(1252).GetString(
					hash.ComputeHash
					(
						Encoding.GetEncoding(1252).GetBytes
						(
							tokens[0] +
							ConfigurationManager.AppSettings["secret"]
						)
					)
				)); // Compute MD5 hash, to store in the cookie, hash with a secret value
		if (md5hashHex != tokens[1])
			return false;
		return true;
	}

	/// <summary>
	/// Get username and password stored in the cookie
	/// </summary>
	/// <param name="cookie">user login cookie</param>
	/// <returns>usernamae and password array of strings</returns>
	public static String[] GetAuthentication(HttpCookie cookie)
	{
		String[] details = new String[2];
		// split with ':', this is my own format
		String[] tokens = cookie.Value.Split(new char[] { ':' });
		details[0] = tokens[0];
		// encrypt the password, we don't want them be stored clear text
		details[1] = RC4.Encrypt(ConfigurationManager.AppSettings["secret"], RC4.pack("", tokens[2]), false);
		return details;
	}
}